package api

import (
	"context"
	"errors"
	"user_srv/model"
	"user_srv/model/dao"
	pb "user_srv/proto"
)

type UserServer struct {
	pb.UnimplementedUserServer
}

func (u *UserServer) Login(ctx context.Context, req *pb.LoginRequest) (resp *pb.LoginResponse, err error) {

	key := "login:" + req.Mobile
	mobile, err := dao.GetUserByMobile(req.Mobile)
	if err != nil {
		user := model.User{
			Mobile: req.Mobile,
		}
		err = dao.Create(user)
		if err != nil {
			return nil, err
		}
	}
	code := dao.GetCode(key)
	if code != req.Code {
		return nil, errors.New("验证码输入有误")
	}
	return &pb.LoginResponse{
		Success: true,
		Uid:     int32(mobile.ID),
	}, nil
}
func (u *UserServer) Code(ctx context.Context, req *pb.CodeRequest) (resp *pb.CodeResponse, err error) {

	key := "login:" + req.Mobile
	code := dao.SetCode(key)
	return &pb.CodeResponse{
		Success: true,
		Code:    code,
	}, nil
}
